package com.xudow.app.newui;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.activeshare.edu.ucenter.models.user.UserProfileWithOther;
import com.xudow.app.R;
import com.xudow.app.newui.base.BaseUiActivity;
import com.xudow.app.newui.bean.UserListStudentMessage;
import com.xudow.app.ui.task.StudentListTask;
import com.xudow.app.ui.task.user.RelatedParentTask;
import com.xudow.app.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

/**
 * 作者：LownChen on 2016/6/12 11:27
 */
public class RelatedParentActivity extends BaseUiActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    @BindView(R.id.related_mobliephone_et)
    EditText related_mobliephone_et;//关联号码

    @BindView(R.id.child_list)
    ListView child_list;//学生列表

    @BindView(R.id.commit_tv)
    TextView commit_tv;//提交

    List<UserListStudentMessage.ChildListEntity> data;
    ChildAdapter adapter;
    List<String> childIds;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_related_parent);
    }

    @Override
    protected void initData() {
        childIds=new ArrayList<String>();
        data=new ArrayList<UserListStudentMessage.ChildListEntity>();
        adapter=new ChildAdapter(this);
        child_list.setAdapter(adapter);
        child_list.setDivider(null);
        //请求孩子列表
        StudentListTask getstudent=new StudentListTask(this,getstudentHandler);
        addTask(getstudent);
        getstudent.execute();
        showLodingDialog("正在处理");
    }

    private Handler getstudentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            hideLoadingDialog();
            if (msg.what==StudentListTask.SUCCESS){

                Bundle bundle=msg.getData();
                UserListStudentMessage.ChildListEntity[] arr=(UserListStudentMessage.ChildListEntity[])bundle.getSerializable("students");
                if (null!=arr&&arr.length>0) {
                    data.clear();

                data.addAll(Arrays.asList(arr));
                adapter.setData(data);
                }

            }else
                getMyApp().makeToast("网络获取失败");
        }
    };

    @Override
    protected void initListener() {
        commit_tv.setOnClickListener(this);
        child_list.setOnItemClickListener(this);
        related_mobliephone_et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

            }
        });
    }
    public void onBackBtnClick(View v){
        finish();
    }
    @Override
    public void onClick(View v) {
        if (childIds.size()==0){
            getMyApp().makeToast("请选择要授权的学生");
        return;
        }
        String cellphone = related_mobliephone_et.getText().toString().trim();
        if (StringUtils.isEmpty(cellphone)) {
            related_mobliephone_et.setError(getString(R.string.cellphone_required));
            return;
        }

        if (!StringUtils.isMobile(cellphone)) {
            related_mobliephone_et.setError(getString(R.string.cellphone_format_err));
            return;
        }
            if (v.getId()==R.id.commit_tv){//提交关联
                HashMap<String,String> pramers=new HashMap<String, String>();
                pramers.put("phone",cellphone);
                pramers.put("studentids",getChildIds());
                Log.e("onClick: ", getChildIds()+"--"+cellphone);
                RelatedParentTask task=new RelatedParentTask(this,commHandler);
                addTask(task);
                task.execute(pramers);
                showLodingDialog("正在处理");
            }
    }
    private Handler commHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            hideLoadingDialog();
            if (msg.what==RelatedParentTask.SUCCESS){
                getMyApp().makeToast((String)msg.obj);
                finish();
            }else
                getMyApp().makeToast((String)msg.obj);
        }
    };
    private String getChildIds(){
        StringBuffer str=new StringBuffer();
        for (String s:childIds) {
            str.append(s);
            str.append(",");
        }
        str.deleteCharAt(str.length()-1);
        return str.toString();
    }
    /**
     * childlist item点击
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        UserListStudentMessage.ChildListEntity child=data.get(position);
        String str=child.getId()+"";
//        child.isSelected=!child.isSelected;
//        if (child.isSelected){

            if (!childIds.contains(str)){
                childIds.add(str);
            }
//        }else{
            if (childIds.contains(str)){
                childIds.remove(str);
            }
//        }

        adapter.notifyDataSetChanged();
    }


    class ChildAdapter extends BaseAdapter{
        private Context context;
        private List<UserListStudentMessage.ChildListEntity> data;

        public ChildAdapter(Context context){
            this.context=context;
        }
        public void setData(List<UserListStudentMessage.ChildListEntity> data){
            this.data=data;
            notifyDataSetChanged();
        }
        @Override
        public int getCount() {
            if (null==data||data.size()==0)
                return 0;
            else
                return data.size();
        }

        @Override
        public UserListStudentMessage.ChildListEntity getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View v, ViewGroup parent) {
            ViewHolder holder;
            if (null==v){
                holder=new ViewHolder();
                v=View.inflate(context,R.layout.item_relatedchild_list,null);
                holder.name=(TextView)v.findViewById(R.id.child_name);
                holder.selectedIv=(ImageView)v.findViewById(R.id.child_select_img);
                v.setTag(holder);
            }else
                holder=(ViewHolder)v.getTag();
            UserListStudentMessage.ChildListEntity child=data.get(position);
                holder.name.setText(child.getName());
//                if (child.isSelected)
//                    holder.selectedIv.setImageResource(R.mipmap.btn_cart_checked);
//                else
                    holder.selectedIv.setImageResource(R.mipmap.btn_cart_unchecked);
            return v;
        }
        class ViewHolder{
            TextView name;
            ImageView selectedIv;
        }
    }
}
